//
//  RootViewController.m
//  ThuePhongDep
//
//  Created by Huynh Chi Hung on 7/15/13.
//  Copyright (c) 2013 Huynh Chi Hung. All rights reserved.
//

#import "RootViewController.h"
#import "ActivityIndicator.h"
#import "JPSThumbnailAnnotation.h"
#import "NSURLConnectionWithTag.h"
#import "RoomDetailView.h"
#import "HouseDetailView.h"


#define API_SERCRET_KEY @"3eac3f982fd8d14919e92df28efcf0481b294a3efe4e7a987a1ab74ce1d1df80aacf02b57ea1f51057ffae73b9b60b9811eb990459b6c2b7777c0432306fb291"
#define DATA_LIMIT            10

#define _TAG_CELL_IMAGE                 1000
#define _TAG_CELL_LTITLE                1001
#define _TAG_CELL_RTITLE                1002
#define _TAG_CELL_CONTENT               1003
#define _TAG_CELL_SUB                   1004
#define _TAG_CELL_SPINNER               1005

#define _TAG_BUTTON_MENU                1010
#define _TAG_BUTTON_LOCATION            1011

#define _TAG_REQUEST_LIST_ROOM          2000
#define _TAG_REQUEST_DETAIL_ROOM        2001

#define _TAG_REQUEST_LIST_HOUSE         2010
#define _TAG_REQUEST_DETAIL_HOUSE       2011

@interface RootViewController ()

@end

@implementation RootViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        arrayData = [[NSMutableArray alloc] init];
        receivedDataByTag = [[NSMutableDictionary alloc] init];
    }
    return self;
}

- (void) dealloc {
    [super dealloc];
    [arrayData release];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    int size = 80;
    
    if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad)
        size = 160;

    _paperFoldView = [[PaperFoldView alloc] initWithFrame:CGRectMake(0,0,[self.view bounds].size.width,[self.view bounds].size.height)];
    [_paperFoldView setAutoresizingMask:UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth];
    [self.view addSubview:_paperFoldView];
    [_paperFoldView release];
    
    _mapView = [[MKMapView alloc] initWithFrame:CGRectMake(0,0,self.view.frame.size.width - size,[self.view bounds].size.height)];
//    [_mapView setShowsUserLocation:YES];
    [_mapView setUserTrackingMode:MKUserTrackingModeFollow];
    _mapView.delegate = self;
    [_paperFoldView setRightFoldContentView:_mapView foldCount:3 pullFactor:0.9];
    
    UIView *_centerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,[self.view bounds].size.width,[self.view bounds].size.height)];
    _centerView.layer.shadowColor = [UIColor blackColor].CGColor;
    _centerView.layer.shadowOpacity = 0.6f;
    [_paperFoldView setCenterContentView:_centerView];
    [_centerView release];

    _centerTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,45,_centerView.frame.size.width,_centerView.frame.size.height-50)];
    
    [_centerTableView setRowHeight:size];

    [_centerTableView setDelegate:self];
    [_centerTableView setDataSource:self];
    _centerTableView.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];

    [_centerView addSubview:_centerTableView];
    [_centerTableView release];

    UIToolbar *toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, _centerView.frame.size.width, 45)];
    [toolBar setBackgroundImage:[UIImage imageNamed:@"menubar_background"] forToolbarPosition:UIToolbarPositionAny barMetrics:UIBarMetricsDefault];
    toolBar.layer.shadowColor = [UIColor blackColor].CGColor;
    toolBar.layer.shadowOffset = CGSizeMake(0, 0);
    toolBar.layer.shadowRadius = 2;
    toolBar.layer.shadowOpacity = 0.6f;

    [_centerView addSubview:toolBar];
    [toolBar release];
    
    UIBarButtonItem *menuButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_menu"] style:UIBarButtonItemStylePlain target:self action:@selector(barButtonTap:)];
    menuButton.tag = _TAG_BUTTON_MENU;

    UIBarButtonItem *locationButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_location"] style:UIBarButtonItemStylePlain target:self action:@selector(barButtonTap:)];
    locationButton.tag = _TAG_BUTTON_LOCATION;
    
    UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

    toolBar.items = [NSArray arrayWithObjects:menuButton,flex,locationButton, nil];
    [menuButton release];
    [flex release];
    [locationButton release];
    
    _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0,150,[self.view bounds].size.height)];
    [_leftTableView setBackgroundColor:[UIColor colorWithRed:53/255.f green:55/255.f blue:63/255.f alpha:1.0]];
    [_leftTableView setRowHeight:45];
//    _leftTableView.separatorColor = [UIColor colorWithRed:101/255.f green:104/255.f blue:111/255.f alpha:0.5];
    _leftTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_leftTableView setDataSource:self];
    [_leftTableView setDelegate:self];
    [_paperFoldView setLeftFoldContentView:_leftTableView foldCount:2 pullFactor:0.9];
    [_leftTableView release];
    
    [_paperFoldView setDelegate:self];
    
    // you may want to disable dragging to preserve tableview swipe functionality
    
    // disable left fold
    //[_paperFoldView setEnableLeftFoldDragging:NO];
    
    // disable right fold
    //[_paperFoldView setEnableRightFoldDragging:NO];
    
//    _topView = [[UIView alloc] initWithFrame:CGRectMake(0,0,[self.view bounds].size.width,300)];
//    [_topView setBackgroundColor:[UIColor whiteColor]];
//    UILabel *topLabel = [[UILabel alloc] initWithFrame:_topView.frame];
//    [topLabel setText:@"A"];
//    [topLabel setBackgroundColor:[UIColor clearColor]];
//    [topLabel setFont:[UIFont boldSystemFontOfSize:300]];
//    [topLabel setTextAlignment:NSTextAlignmentCenter];
//    [_topView addSubview:topLabel];
//    
//    ShadowView *topShadowView = [[ShadowView alloc] initWithFrame:CGRectMake(0,_topView.frame.size.height-5,_topView.frame.size.width,5) foldDirection:FoldDirectionVertical];
//    [topShadowView setColorArrays:@[[UIColor colorWithWhite:0 alpha:0.3],[UIColor clearColor]]];
//    [_topView addSubview:topShadowView];
//    
//    [_paperFoldView setTopFoldContentView:_topView topViewFoldCount:5 topViewPullFactor:0.9];
    
//    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0,0,[self.view bounds].size.width,160)];
//    UILabel *bottomLabel = [[UILabel alloc] initWithFrame:_bottomView.frame];
//    [bottomLabel setText:@"A"];
//    [bottomLabel setFont:[UIFont boldSystemFontOfSize:150]];
//    [bottomLabel setTextAlignment:NSTextAlignmentCenter];
//    [_bottomView addSubview:bottomLabel];
//    
//    ShadowView *bottomShadowView = [[ShadowView alloc] initWithFrame:CGRectMake(0,0,_topView.frame.size.width,5) foldDirection:FoldDirectionVertical];
//    [bottomShadowView setColorArrays:@[[UIColor clearColor],[UIColor colorWithWhite:0 alpha:0.3]]];
//    [_bottomView addSubview:bottomShadowView];
//    
//    [_paperFoldView setBottomFoldContentView:_bottomView];
    
//#warning disabling scroll, requires tapping cell twice to select cells. to be fixed
    //[_paperFoldView setEnableHorizontalEdgeDragging:YES];

    [self requestRoomList];
    _totalData = 0;
    _isEndData  =  NO;
    _selectedMenu = 0;
}

#pragma table view
-  (void)barButtonTap:(id)sender {
    UIBarButtonItem *button = (UIBarButtonItem*) sender;
    if (button.tag ==_TAG_BUTTON_MENU ) {
        if (self.paperFoldView.state != PaperFoldStateLeftUnfolded)
            [self.paperFoldView setPaperFoldState:PaperFoldStateLeftUnfolded];
        else
            [self.paperFoldView setPaperFoldState:PaperFoldStateDefault];
    }
    else if (button.tag ==_TAG_BUTTON_LOCATION) {
        if (self.paperFoldView.state != PaperFoldStateRightUnfolded)
            [self.paperFoldView setPaperFoldState:PaperFoldStateRightUnfolded];
        else
            [self.paperFoldView setPaperFoldState:PaperFoldStateDefault];
    }

}

#pragma table view

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView)
        return 45;
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (tableView == _leftTableView) {
        static NSString* boldFontName = @"Avenir-Black";
        UIView *header = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 50)] autorelease];
        header.backgroundColor = [UIColor colorWithRed:53/255.f green:55/255.f blue:63/255.f alpha:1.0];
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(7, 7, 30, 30)];
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        imageView.image = [UIImage imageNamed:@"logo_header"];
        [header addSubview:imageView];
        [imageView release];
        
        UILabel *labelTile = [[UILabel alloc] initWithFrame:CGRectMake(43, 12, 100, 20)];
        labelTile.textColor = [UIColor whiteColor];
        labelTile.font = [UIFont fontWithName:boldFontName size:12];
        labelTile.textAlignment = NSTextAlignmentLeft;
        labelTile.backgroundColor = [UIColor clearColor];
        labelTile.text = @"PHÒNG ĐẸP.VN";
        labelTile.adjustsFontSizeToFitWidth = YES;
        [header addSubview:labelTile];
        [labelTile release];

        return header;
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView==self.leftTableView)
        return 3;
    else
        return [arrayData count];
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    int fontSize = 14;
    
    if([UIDevice currentDevice].userInterfaceIdiom==UIUserInterfaceIdiomPad)
        fontSize = 18;

    static NSString *identifierCellLeft = @"UITableViewCellLeft";
    static NSString *identifierCellCenter = @"UITableViewCellCenter";
    static NSString* fontName = @"Avenir";
    static NSString* boldFontName = @"Avenir-Black";

    UITableViewCell *cell = nil;
    if (tableView==self.leftTableView)
    {
        cell = [tableView dequeueReusableCellWithIdentifier:identifierCellLeft];
        if (!cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierCellLeft] autorelease];
            UIView *myBackView = [[UIView alloc] initWithFrame:cell.frame];
            myBackView.backgroundColor = [UIColor colorWithWhite:244/255.f alpha:1.0];
            [cell setSelectedBackgroundView:myBackView];
            [myBackView release];
            cell.textLabel.highlightedTextColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
            cell.textLabel.textColor = [UIColor whiteColor];
            cell.textLabel.font = [UIFont fontWithName:boldFontName size:14];
            UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, cell.frame.size.height, cell.frame.size.width, 1)];
            line.backgroundColor = [UIColor colorWithRed:101/255.f green:104/255.f blue:111/255.f alpha:0.5];
            [cell.contentView addSubview:line];
            [line release];
        }
        
        if ([indexPath row] == 0) {
            [cell.textLabel setText:@"Phòng"];
            cell.imageView.image = [UIImage imageNamed:@"icon_room"];
        }
        else if ([indexPath row] == 1) {
            [cell.textLabel setText:@"Nhà"];
            cell.imageView.image = [UIImage imageNamed:@"icon_home"];
            
        }
        else if ([indexPath row] == 2) {
            [cell.textLabel setText:@"Liên Hệ"];
            cell.imageView.image = [UIImage imageNamed:@"icon_contact"];
        }
//        else if ([indexPath row] == 3) {
//            [cell.textLabel setText:@"Giới thiệu"];
//        }

    }
    else {
        cell = [tableView dequeueReusableCellWithIdentifier:identifierCellCenter];
        if (!cell) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifierCellCenter] autorelease];
            cell.backgroundColor = [UIColor clearColor];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - tableView.rowHeight, 0, tableView.rowHeight, tableView.rowHeight)];
            imageView.tag = _TAG_CELL_IMAGE;
            imageView.layer.borderColor = [UIColor whiteColor].CGColor;
            imageView.layer.borderWidth = 3.0f;
            imageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            [cell.contentView addSubview:imageView];
            [imageView release];
            
            UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc]
                                                initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
            spinner.center = CGPointMake(imageView.frame.size.width / 2, imageView.frame.size.height / 2);
            spinner.tag = _TAG_CELL_SPINNER;
            spinner.autoresizingMask = UIViewAutoresizingFlexibleTopMargin
            | UIViewAutoresizingFlexibleRightMargin
            | UIViewAutoresizingFlexibleBottomMargin
            | UIViewAutoresizingFlexibleLeftMargin;
            spinner.color = UIColor.lightGrayColor;
            [imageView addSubview:spinner];
            [spinner release];

            
            UILabel *labelTile = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, cell.contentView.frame.size.width - 140 - tableView.rowHeight - 10, 30)];
            labelTile.tag = _TAG_CELL_LTITLE;
            labelTile.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
            labelTile.font = [UIFont fontWithName:boldFontName size:fontSize];
            labelTile.textAlignment = NSTextAlignmentLeft;
            labelTile.backgroundColor = [UIColor clearColor];
            labelTile.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            [cell.contentView addSubview:labelTile];
            [labelTile release];
            
            labelTile = [[UILabel alloc] initWithFrame:CGRectMake(cell.contentView.frame.size.width - 140 - tableView.rowHeight, 0, 110, 30)];
            labelTile.textColor = [UIColor colorWithRed:215/255.f green:99/255.f blue:78/255.f alpha:1.0];
            labelTile.tag = _TAG_CELL_RTITLE;
            labelTile.font = [UIFont fontWithName:boldFontName size:fontSize];
            labelTile.textAlignment = NSTextAlignmentRight;
            labelTile.backgroundColor = [UIColor clearColor];
            labelTile.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
            [cell.contentView addSubview:labelTile];
            [labelTile release];

            labelTile = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, cell.contentView.frame.size.width - tableView.rowHeight - 10, tableView.rowHeight - 30)];
            labelTile.textColor = [UIColor colorWithRed:52/255.f green:56/255.f blue:60/255.f alpha:1.0];
            labelTile.tag = _TAG_CELL_CONTENT;
            labelTile.backgroundColor = [UIColor clearColor];
            labelTile.font = [UIFont fontWithName:fontName size:fontSize-2];
            labelTile.adjustsFontSizeToFitWidth =  YES;
            labelTile.numberOfLines = 3;
            labelTile.autoresizingMask = UIViewAutoresizingFlexibleWidth;
            [cell.contentView addSubview:labelTile];
            [labelTile release];

//            labelTile = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, cell.contentView.frame.size.width - 100, 30)];
//            labelTile.tag = _TAG_CELL_SUB;
//            labelTile.backgroundColor = [UIColor clearColor];
//            [cell.contentView addSubview:labelTile];
//            [labelTile release];
        }
        
        NSDictionary *dict = [arrayData objectAtIndex:[indexPath row]];
        
//        NSString *roomName = [[receivedDict allKeys] objectAtIndex:[indexPath row]];
        NSString *roomName = [dict objectForKey:@"KEY"]; // Assumes 'message' is not empty

//        NSDictionary *roomDetail = (NSDictionary *) [receivedDict objectForKey:roomName];
        NSDictionary *roomDetail = (NSDictionary *) [dict objectForKey:@"VALUE"];

        NSString *imageURL = [roomDetail objectForKey:@"image"];
        UIImageView *imageView = (UIImageView *) [cell.contentView viewWithTag:_TAG_CELL_IMAGE];

        UIActivityIndicatorView *spinner =  (UIActivityIndicatorView*) [cell.contentView viewWithTag:_TAG_CELL_SPINNER];
        
        if ([[ImageCache sharedImageCache] DoesExist:imageURL] == true)
        {
            imageView.image = [[ImageCache sharedImageCache] GetImage:imageURL];
            spinner.hidden = YES;
            [spinner stopAnimating];
        }
        else
        {
            spinner.hidden = NO;
            [spinner startAnimating];
            imageView.image = [UIImage imageNamed:@"default_image"];
            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
            dispatch_async(queue, ^{
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
                UIImage *image = [UIImage imageWithData:data];
                if (image)
                    [[ImageCache sharedImageCache] AddImage:image withURL:imageURL];
                dispatch_async(dispatch_get_main_queue(), ^{
                    if (image) {
                        UIImageView *imageView = (UIImageView*) [[tableView cellForRowAtIndexPath:indexPath] viewWithTag:_TAG_CELL_IMAGE];
                        if (imageView) {
                            imageView.image = image;
                            [spinner stopAnimating];
                            spinner.hidden = YES;
                        }
                        else {
                            NSLog(@"invisible cell");
                        }
                    }
                });
            });
            
//            NSData *imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: imageURL]];
//            imageView.image = [[[UIImage alloc] initWithData:imageData] autorelease];
            // Add the image to the cache
//            if (imageView.image)
//            [imageData release];
        }
        
        UILabel *labelTile = (UILabel*) [cell.contentView viewWithTag:_TAG_CELL_LTITLE];
        labelTile.text = roomName;
        
        NSNumberFormatter *numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
        numberFormatter.groupingSeparator = @".";
        numberFormatter.decimalSeparator = @",";
        [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];


        labelTile = (UILabel*) [cell.contentView viewWithTag:_TAG_CELL_RTITLE];
        if (_selectedMenu == 0) {
            CGFloat price = [[roomDetail objectForKey:@"price"] floatValue];
            labelTile.text = [NSString stringWithFormat:@"%@",
                              [numberFormatter stringFromNumber:[NSNumber numberWithFloat:price]]];
        }
        else {
            labelTile.text = @"";
        }

        labelTile = (UILabel*) [cell.contentView viewWithTag:_TAG_CELL_CONTENT];
        NSString *address = [roomDetail objectForKey:@"address"];
        NSString *district = [roomDetail objectForKey:@"district"];
        NSString *city = [roomDetail objectForKey:@"city"];
        labelTile.text = [NSString stringWithFormat:@"Địa chỉ: %@, Quận %@, Tỉnh/TP %@.",address,district,city];

    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView==self.centerTableView) {
        if (self.paperFoldView.state != PaperFoldStateRightUnfolded)
            [self.paperFoldView setPaperFoldState:PaperFoldStateRightUnfolded];
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
        _selectedRow = indexPath.row;
        NSDictionary *dict = [arrayData objectAtIndex:[indexPath row]];
        NSString *name = [dict objectForKey:@"KEY"]; // Assumes 'message' is not empty
        
        for (id annotation in _mapView.annotations) {
            if ([annotation isKindOfClass:[JPSThumbnailAnnotation class]]) {
                JPSThumbnailAnnotation *thumbnailAnnotation = (JPSThumbnailAnnotation*) annotation;
                if ([thumbnailAnnotation.thumbnail.title isEqualToString:name]) {
                    [_mapView selectAnnotation:thumbnailAnnotation animated:YES];
                    break;
                }                
            }
        }
    }
    else if (tableView==self.leftTableView && indexPath.row < 2) {
        [self.paperFoldView setPaperFoldState:PaperFoldStateDefault];
        if (indexPath.row !=_selectedMenu) {
            _selectedMenu = indexPath.row;
            // Reset state
            _totalData = 0;
            _isEndData  =  NO;
            [arrayData removeAllObjects];
            [_centerTableView reloadData];
            // Remove all annotation
            NSLog(@"count %d",[_mapView.annotations count]);

            //copy your annotations to an array
            NSMutableArray *annotationsToRemove = [[NSMutableArray alloc] initWithArray: _mapView.annotations];
            //Remove the object userlocation
            [annotationsToRemove removeObject: _mapView.userLocation];
            //Remove all annotations in the array from the mapView
            [_mapView removeAnnotations: annotationsToRemove];
            [annotationsToRemove release];
            
            if(_selectedMenu == 0) {
                [self requestRoomList];
            }
            else {
                [self requestHouseList];
            }
        }
    }
}

#pragma mark paper fold delegate

- (void)paperFoldView:(id)paperFoldView didFoldAutomatically:(BOOL)automated toState:(PaperFoldState)paperFoldState
{
//    NSLog(@"did transition to state %i automated %i", paperFoldState, automated);
}


#pragma mark - MKMapViewDelegate

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKAnnotationView *)view {
    if ([view conformsToProtocol:@protocol(JPSThumbnailAnnotationViewProtocol)]) {
        [((NSObject<JPSThumbnailAnnotationViewProtocol> *)view) didSelectAnnotationViewInMap:mapView];
    }

    if ([view.annotation isKindOfClass:[JPSThumbnailAnnotation class]]) {
        for (NSDictionary *dict in arrayData) {
            NSString *roomName = [dict objectForKey:@"KEY"]; // Assumes 'message' is not empty
            JPSThumbnailAnnotation *annotation = (JPSThumbnailAnnotation*) view.annotation;
            if ([annotation.thumbnail.title isEqualToString:roomName]) {
                _selectedRow = [arrayData indexOfObject:dict];
                break;
            }
        }
    }
}

- (void)mapView:(MKMapView *)mapView didDeselectAnnotationView:(MKAnnotationView *)view {
    if ([view conformsToProtocol:@protocol(JPSThumbnailAnnotationViewProtocol)]) {
        [((NSObject<JPSThumbnailAnnotationViewProtocol> *)view) didDeselectAnnotationViewInMap:mapView];
    }
}

- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation {
    if ([annotation conformsToProtocol:@protocol(JPSThumbnailAnnotationProtocol)]) {
        return [((NSObject<JPSThumbnailAnnotationProtocol> *)annotation) annotationViewInMap:mapView];
    }
    return nil;
}

- (void)showDetail {
    if (_selectedMenu == 0) {
        NSDictionary *dict = [arrayData objectAtIndex:_selectedRow];
        NSDictionary *roomDetail = (NSDictionary *) [dict objectForKey:@"VALUE"];
        NSLog(@"%@",roomDetail);
        RoomDetailView *roomDetailView = [[RoomDetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                                                         title:[dict objectForKey:@"KEY"]
                                                                        roomID:[roomDetail objectForKey:@"roomid"]];
        roomDetailView.parentController = self;
        [self.view addSubview:roomDetailView];
        // Show the panel from the center of the button that was pressed
        [roomDetailView showFromPoint:[self.view center]];
        [roomDetailView release];
    }
    else if (_selectedMenu == 1) {
        NSDictionary *dict = [arrayData objectAtIndex:_selectedRow];
        NSDictionary *houseDetail = (NSDictionary *) [dict objectForKey:@"VALUE"];
        NSLog(@"%@",houseDetail);
        HouseDetailView *houseDetailView = [[HouseDetailView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)
                                                                         title:[dict objectForKey:@"KEY"]
                                                                        houseID:[houseDetail objectForKey:@"houseid"]];
        houseDetailView.parentController = self;
        [self.view addSubview:houseDetailView];
        // Show the panel from the center of the button that was pressed
        [houseDetailView showFromPoint:[self.view center]];
        [houseDetailView release];
    }
}



- (void)willCloseModalPanel:(UAModalPanel *)modalPanel {
    [_mapView layoutSubviews];
}

#pragma mark Web Service

-(void)requestHouseList {
//    [ActivityIndicator currentIndicator].center = self.view.center;
//    [[ActivityIndicator currentIndicator] displayActivity:@"Đang tra cứu"];
    NSString *requestURL = [NSString stringWithFormat:@"http://phongdep.vn/ws/house_list?secret_key=%@&offset=%d&limit=%d",API_SERCRET_KEY,_totalData,DATA_LIMIT];
    NSLog(@"%@",requestURL);
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnectionWithTag *connection=[[NSURLConnectionWithTag alloc] initWithRequest:theRequest delegate:self tag:_TAG_REQUEST_LIST_HOUSE];
    if (connection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        
        if ([receivedDataByTag objectForKey:connection.tag]) {
            [receivedDataByTag removeObjectForKey:connection.tag];
        }
        [receivedDataByTag setObject:[NSMutableData data] forKey:connection.tag];
    } else {
        // Inform the user that the connection failed.
        NSLog(@"connection failed");
        _finishLoad = YES;
        [[ActivityIndicator currentIndicator] hide];
    }
}

-(void)requestRoomList {
//    [[ActivityIndicator currentIndicator] displayActivity:@"Đang tra cứu"];
    // Create the request.
    NSString *requestURL = [NSString stringWithFormat:@"http://phongdep.vn/ws/free_rooms?secret_key=%@&offset=%d&limit=%d",API_SERCRET_KEY,_totalData,DATA_LIMIT];
    NSLog(@"%@",requestURL);
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:requestURL]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:60.0];
    // create the connection with the request
    // and start loading the data
    NSURLConnectionWithTag *connection = [[NSURLConnectionWithTag alloc] initWithRequest:theRequest delegate:self tag:_TAG_REQUEST_LIST_ROOM];

    if (connection) {
        // Create the NSMutableData to hold the received data.
        // receivedData is an instance variable declared elsewhere.
        
        if ([receivedDataByTag objectForKey:connection.tag]) {
            [receivedDataByTag removeObjectForKey:connection.tag];
        }        
        [receivedDataByTag setObject:[NSMutableData data] forKey:connection.tag];
    } else {
        // Inform the user that the connection failed.
        NSLog(@"connection failed");
        [connection release];
        _finishLoad = YES;
        [[ActivityIndicator currentIndicator] hide];
    }
}

-(void)connection:(NSURLConnectionWithTag *)connection didReceiveData:(NSData *)data {
        if ([receivedDataByTag objectForKey:connection.tag] == nil) {
            NSMutableData *newData = [[NSMutableData alloc] initWithData:data];
            [receivedDataByTag setObject:newData forKey:connection.tag];
            [newData release];
        } else {
            [[receivedDataByTag objectForKey:connection.tag] appendData:data];
        }
}
/*
 if there is an error occured, this method will be called by connection
 */

-(void)connection:(NSURLConnectionWithTag *)connection didFailWithError:(NSError *)error{
    [receivedDataByTag removeObjectForKey:connection.tag];
    [connection release];
    _finishLoad = YES;
    [[ActivityIndicator currentIndicator] hide];
}

/*
 if data is successfully received, this method will be called by connection
 */

-(void)connectionDidFinishLoading:(NSURLConnectionWithTag *)connection{
    
    NSError *myError = nil;
    NSDictionary *rectDict= [NSJSONSerialization JSONObjectWithData:[receivedDataByTag objectForKey:connection.tag] options:NSJSONReadingMutableLeaves error:&myError];

    if ([connection.tag intValue] == _TAG_REQUEST_LIST_ROOM) {
    
//        NSString *responseString = [[[NSString alloc] initWithData:[receivedDataByTag objectForKey:connection.tag] encoding:NSUTF8StringEncoding] autorelease];
//        responseString = [responseString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//        
//        NSLog(@"Succeeded! Received JSON String %@ ",responseString);
        // release the connection, and the data object
        
        // show all values
        for(id mainKey in rectDict) {
            NSString *keyAsString = (NSString *)mainKey;

            if ([keyAsString isEqualToString:@"data"]){
                NSDictionary *mainValue = (NSDictionary *)[rectDict objectForKey:mainKey];
                if ([[mainValue allKeys] count] == 0)
                    break;
                
                if ([mainValue count] == 0) {
                    _isEndData = YES;
                    break;
                }
                
                if ([[mainValue allKeys] count] < DATA_LIMIT){
                    _isEndData = YES;
                }
                _totalData = _totalData + [[mainValue allKeys] count];
                
                for (id subKey in mainValue) {
                    NSString *subKeyAsString = (NSString *)subKey;
                    id subValue = [mainValue objectForKey:subKey];
                    if (subValue) {
                        NSDictionary *tmpDict = [[NSDictionary alloc] initWithObjectsAndKeys:subKeyAsString,@"KEY",
                                                 subValue,@"VALUE",nil];
                        [arrayData addObject:tmpDict];
                        [tmpDict release];
                        
                        NSDictionary *roomDetail = (NSDictionary*) subValue;
                        NSDictionary *location = [roomDetail objectForKey:@"location"];

                        if ([location objectForKey:@"latitude"] != [NSNull null] &&
                            [location objectForKey:@"longitude"] != [NSNull null]) {
                            NSString *imageURL = [roomDetail objectForKey:@"image"];
                            JPSThumbnail *thumbnail = [[JPSThumbnail alloc] init];
                            thumbnail.title = subKeyAsString;
                            NSString *address = [roomDetail objectForKey:@"address"];
                            NSString *district = [roomDetail objectForKey:@"district"];
                            NSString *city = [roomDetail objectForKey:@"city"];
                            thumbnail.subtitle = [NSString stringWithFormat:@"%@, Q. %@, Tỉnh/TP %@.",address,district,city];
                            thumbnail.disclosureBlock = ^{ [self showDetail]; };
                            
                            
                            thumbnail.coordinate = CLLocationCoordinate2DMake([[location objectForKey:@"latitude"] doubleValue],
                                                                              [[location objectForKey:@"longitude"] doubleValue]);
                            
                            if ([[ImageCache sharedImageCache] DoesExist:imageURL] == true)
                            {
                                thumbnail.image = [[ImageCache sharedImageCache] GetImage:imageURL];
                                
                                JPSThumbnailAnnotation *annotation = [[JPSThumbnailAnnotation alloc] initWithThumbnail:thumbnail];
                                [_mapView addAnnotation:annotation];
                                [thumbnail release];
                                [annotation release];
                                
                            }
                            else
                            {
                                thumbnail.image = [UIImage imageNamed:@"default_image"];
                                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
                                dispatch_async(queue, ^{
                                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
                                    UIImage *image = [UIImage imageWithData:data];
                                    if (image)
                                        [[ImageCache sharedImageCache] AddImage:image withURL:imageURL];
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        if (image) {
                                            thumbnail.image = image;
                                            JPSThumbnailAnnotation *annotation = [[JPSThumbnailAnnotation alloc] initWithThumbnail:thumbnail];
                                            [_mapView addAnnotation:annotation];
                                            [thumbnail release];
                                            [annotation release];
                                        }
                                        else {
                                        }
                                    });
                                });
                            }
                        }
                        else {
                            continue;
                        }
                    }
                }
                [_centerTableView reloadData];
            }
        }
    }
    else if ([connection.tag intValue] == _TAG_REQUEST_LIST_HOUSE) {
        for(id mainKey in rectDict) {
            NSString *keyAsString = (NSString *)mainKey;
            
            if ([keyAsString isEqualToString:@"data"]){
                NSDictionary *mainValue = (NSDictionary *)[rectDict objectForKey:mainKey];

                if ([mainValue count] == 0) {
                    _isEndData = YES;
                    break;
                }                            
                    
                if ([[mainValue allKeys] count] < DATA_LIMIT){
                    _isEndData = YES;
                }
                _totalData = _totalData + [[mainValue allKeys] count];
                
                for (id subKey in mainValue) {
                    NSString *subKeyAsString = (NSString *)subKey;
                    id subValue = [mainValue objectForKey:subKey];
                    if (subValue) {
                        NSDictionary *tmpDict = [[NSDictionary alloc] initWithObjectsAndKeys:subKeyAsString,@"KEY",
                                                 subValue,@"VALUE",nil];
                        [arrayData addObject:tmpDict];
                        [tmpDict release];

                        
                        NSDictionary *houseDetail = (NSDictionary*) subValue;
                        NSDictionary *location = [houseDetail objectForKey:@"location"];
                        
                        NSLog(@"location %@",location);
                        if ([location objectForKey:@"latitude"] != [NSNull null] &&
                            [location objectForKey:@"longitude"] != [NSNull null]) {
                            NSString *imageURL = [houseDetail objectForKey:@"image"];
                            JPSThumbnail *thumbnail = [[JPSThumbnail alloc] init];
                            thumbnail.title = subKeyAsString;
                            NSString *address = [houseDetail objectForKey:@"address"];
                            NSString *district = [houseDetail objectForKey:@"district"];
                            NSString *city = [houseDetail objectForKey:@"city"];
                            thumbnail.subtitle = [NSString stringWithFormat:@"%@, Q. %@, Tỉnh/TP %@.",address,district,city];
                            thumbnail.disclosureBlock = ^{ [self showDetail]; };
                            thumbnail.coordinate = CLLocationCoordinate2DMake([[location objectForKey:@"latitude"] doubleValue],
                                                                              [[location objectForKey:@"longitude"] doubleValue]);
                            
                            if ([[ImageCache sharedImageCache] DoesExist:imageURL] == true)
                            {
                                thumbnail.image = [[ImageCache sharedImageCache] GetImage:imageURL];
                                
                                JPSThumbnailAnnotation *annotation = [[JPSThumbnailAnnotation alloc] initWithThumbnail:thumbnail];
                                [_mapView addAnnotation:annotation];
                                [thumbnail release];
                                [annotation release];
                                
                            }
                            else
                            {
                                thumbnail.image = [UIImage imageNamed:@"default_image"];
                                dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
                                dispatch_async(queue, ^{
                                    NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
                                    UIImage *image = [UIImage imageWithData:data];
                                    if (image)
                                        [[ImageCache sharedImageCache] AddImage:image withURL:imageURL];
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        if (image) {
                                            thumbnail.image = image;
                                            JPSThumbnailAnnotation *annotation = [[JPSThumbnailAnnotation alloc] initWithThumbnail:thumbnail];
                                            [_mapView addAnnotation:annotation];
                                            [thumbnail release];
                                            [annotation release];
                                            
                                        }
                                        else {
                                        }
                                    });
                                });
                            }

                        }
                        else {
                            continue;
                        }

                    }
                }
                [_centerTableView reloadData];
            }
        }
    }
    
    [receivedDataByTag removeObjectForKey:connection.tag];
    [connection release];
    
    _finishLoad = YES;
    [[ActivityIndicator currentIndicator] hide];
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint offset = scrollView.contentOffset;
    CGRect bounds = scrollView.bounds;
    CGSize size = scrollView.contentSize;
    UIEdgeInsets inset = scrollView.contentInset;
    float y = offset.y + bounds.size.height - inset.bottom;
    float h = size.height;
    
    float reload_distance = 0;
    if(y > h + reload_distance && !_isEndData && _finishLoad) {
        _finishLoad = NO;
        NSLog(@"load more rows");
        [[ActivityIndicator currentIndicator] displayActivity:@"Đang tra cứu"];
        if (_selectedMenu == 0)
            [self requestRoomList];
        else
            [self requestHouseList];
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
